package com.kedou.sdk.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.kedou.sdk.JuHaoWanSDK;
import com.kedou.sdk.params.CreateOrderResponseParams;
import com.kedou.sdk.utils.WL;

/**
 * Created by Administrator on 2017/6/9 0009.
 */

public class WXH5PayActivity extends AppBaseActivity implements H5PayCallback {

    private static final String TAG = WXH5PayActivity.class.getSimpleName();
    private static final int PAY_REQUEST_CODE = 1000;

    private static final String FINISH_ACTIVITY_URL = "http://com.51wansy.cn/?tag=";
    private static final String URL_QUERY_KEY = "tag";

    private WebView mWebClientView;
    private ProgressBar mContentProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        WL.d(TAG, "onCreate -----------> ");
        super.onCreate(savedInstanceState);
        setContentView(getLayoutIdentifier("wan_activity_weixin_h5pay"));
        onInitViews();
        onInitEvent();
    }

    private void onInitViews() {
        mContentProgressBar = findViewById(getViewIdentifier("activity_h5pay_progressbar"));
        mWebClientView = findViewById(getViewIdentifier("activity_weixin_h5pay_webview"));
        WebSettings webSettings = mWebClientView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setSupportZoom(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mWebClientView.addJavascriptInterface(new H5WebPay(), "JSInterface");
    }

    @Override
    public void onBackPressed() {
        if (!isForbidBackSuper()) {
            setResult(RESULT_CANCELED);
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (PAY_REQUEST_CODE == requestCode) {
            finish();
        }
    }

    private void onInitEvent() {

        String ursl = null;
        Intent intent = getIntent();
        if (intent != null) {
            CreateOrderResponseParams.CreateOrderResponseData order = intent.getParcelableExtra("weixinPay");
            if (order != null) {
                ursl = order.getPay_info();
            }
        }

        if (TextUtils.isEmpty(ursl)) {
            return;
        }

        if (ursl.startsWith("weixin:") || ursl.startsWith("alipays:") || ursl.startsWith("alipay")) {
            startActivityForResult(new Intent("android.intent.action.VIEW", Uri.parse(ursl)), PAY_REQUEST_CODE);
        } else {
            mWebClientView.loadUrl(ursl);
            mWebClientView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (mContentProgressBar != null) {
                        if (newProgress == 100) {
                            mContentProgressBar.setVisibility(View.GONE);
                        } else {
                            if (View.VISIBLE != mContentProgressBar.getVisibility()) {
                                mContentProgressBar.setVisibility(View.VISIBLE);
                            }
                            mContentProgressBar.setProgress(newProgress);
                        }

                    }
                    super.onProgressChanged(view, newProgress);
                }
            });

            mWebClientView.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    WL.d(TAG, "shouldOverrideUrlLoading ----->url: " + url);
                    final PayTask task = new PayTask(WXH5PayActivity.this);
                    if (!task.payInterceptorWithUrl(url, true, WXH5PayActivity.this)) {
                        if (!TextUtils.isEmpty(url)) {
                            if (url.contains(FINISH_ACTIVITY_URL)) {
                                String result = Uri.parse(url).getQueryParameter(URL_QUERY_KEY);
                                WL.d(TAG, "shouldOverrideUrlLoading ----->Query Parameter result: " + result);
                                if ("success".equalsIgnoreCase(result)) {
                                    setResult(RESULT_OK);
                                } else {
                                    setResult(RESULT_CANCELED);
                                }
                                finish();
                            } else if (url.startsWith("weixin:") || url.startsWith("alipays:") || url.startsWith("alipay")) {
                                try {
                                    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), PAY_REQUEST_CODE);
                                } catch (Exception e) {
                                    final int resId = getStringIdentifier("hnssn_h5payhint_webclient_excepition");
                                    Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            } else {
                                return super.shouldOverrideUrlLoading(view, url);
                            }

                        }
                    }
                    return true;
                }
            });
        }
    }

    @Override
    public void onPayResult(H5PayResultModel h5PayResultModel) {
        // 支付结果返回
        WL.d(TAG, "onPayResult ----->resultCode: " + h5PayResultModel.getResultCode());

        String resultCode = h5PayResultModel.getResultCode();
        if (TextUtils.equals("9000", resultCode)) {
            setResult(RESULT_OK);
            finish();
        } else if (TextUtils.equals("6001", resultCode)) {
            setResult(RESULT_CANCELED);
            finish();
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }

//        final String url = h5PayResultModel.getReturnUrl();
//        if (!TextUtils.isEmpty(url)) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    mWebClientView.loadUrl(url);
//                }
//            });
//        }
    }

    class H5WebPay {

        @JavascriptInterface
        public void finishActivity(String gameId) {
            WL.d(TAG, "H5WebPay -> finishActivity text: " + gameId);
            final String currentGameId = JuHaoWanSDK.getInstance().getGameId();
            if (TextUtils.equals(gameId, currentGameId)) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }
}
